#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: req_test_case.py
# Author: ChenChangSong
# Date: 2025-11-02

"""
功能描述: 需求关联的测试用例信息（总用例条数，冒烟用例条数）
"""

import json

import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent.parent.parent))

from comm.common_code import *

def req_test_case_info(req_id):
    """根据需求ID获取需求关联的测试用例信息(总用例条数，冒烟用例条数)"""
    excel_data = get_excel_data()
    url = "https://www.tapd.cn/api/entity/tcase/get_list"
    headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'Content-Type': 'application/json',
    'Cookie':  excel_data["Cookie"],
    'Origin': 'https://www.tapd.cn',
    'Referer': f'https://www.tapd.cn/tapd_fe/{excel_data["项目ID"]}/story/detail/{req_id}',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.562.400 QQBrowser/19.6.6725.400',
    'sec-ch-ua': '"Not)A;Brand";v="24", "Chromium";v="116"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"'
    }
    total_case = 0  # 用例总数
    m_y_case_num = 0 # 冒烟用例数
    # 获取冒烟用例条数，当整页没有包含"冒烟"时、或遍历遇到无"冒烟"时停止输出m_y_case_num
    for i in range(1,99):
        payload = json.dumps({
        "workspace_id": f"{excel_data['项目ID']}",
        "entity_id": f"{req_id}",
        "entity_type": "story",
        "page": i,
        "sort_name": "priority",
        "order": "desc",
        "dsc_token": "qeSs1MkPb6GKkSam"
        })
        response_code,response_data = api_request(method="POST", url=url, headers=headers, data=payload)
        if response_code == 200 :
            m_y_case_list =  response_data["data"]["list"]
            total_case_data = int(response_data["data"]["count"])# 总用用例数（包含冒烟)
            total_case += total_case_data
            if m_y_case_list !=[]:
                # 检查当前页是否有冒烟用例
                has_smoke_case_in_page = False
                # 记录是否遇到非冒烟用例
                encountered_non_smoke = False
            
                for m_y_case in m_y_case_list:
                    if m_y_case["priority"] == "冒烟":
                        m_y_case_num += 1
                        has_smoke_case_in_page = True
                    else:
                        # 遇到非冒烟用例
                        encountered_non_smoke = True
                        # 如果已经找到了一些冒烟用例，然后遇到非冒烟用例，则停止当前页的遍历
                        if has_smoke_case_in_page:
                            break
            elif m_y_case_list ==[]:
                logger.info(f"第{i}页用例为空")
                break
            # 如果当前页没有冒烟用例，或者遇到了非冒烟用例且之前有冒烟用例，则停止循环
            if not has_smoke_case_in_page or (has_smoke_case_in_page and encountered_non_smoke):
                break
        else:
            logger.info(f"第{i}页用例获取失败，响应码{response_code}，响应内容{response_data}")
    logger.info(f"执行到第{i}页，用例总数{total_case}，共{m_y_case_num}条冒烟用例")
    return total_case,m_y_case_num


if __name__ == "__main__":
    # 1166606973001059375:无用例，1166606973001059264:第一页冒烟，1166606973001059234:3页冒烟
    req_test_case_info(req_id='1166606973001059375')
